package com.cbtx.networklib

import android.content.Context
import android.util.Pair
import androidx.collection.ArrayMap
import com.cbtx.networklib.config.HostConfig
import com.cbtx.networklib.config.LogConfig
import com.cbtx.networklib.factory.NetworkFactory
import com.cbtx.networklib.interceptor.CommonParamsInterceptor
import com.cbtx.networklib.interceptor.HeaderInterceptor
import com.cbtx.networklib.interceptor.LogInterceptor

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/6/25 4:55 PM
 * desc   :
 */
class ApiServiceHolder<T>(
    private val context: Context,
    private val clazz: Class<T>,
    private val hostConfig: HostConfig,
    private val headers: Map<String, String?> = mutableMapOf()
) {

    init {
        ContextManager.setContext(context)
    }

    lateinit var env: HostConfig.Env
        @Synchronized get
        @Synchronized set

    // alias -> <Env, Service Instance>
    private val serviceMap: MutableMap<String, Pair<HostConfig.Env, T>> = ArrayMap()

    @Synchronized
    fun getApiService(alias: String, isOpenLog: Boolean = BuildConfig.DEBUG, prettyJsonPrinting: Boolean = true): T {
        var servicePair = serviceMap[alias]
        if (servicePair == null || servicePair.first != env) {
            servicePair = Pair.create(
                env,
                createApiService(clazz, hostConfig.getHost(alias, env), isOpenLog, prettyJsonPrinting)
            )
            serviceMap[alias] = servicePair
        }
        return servicePair?.second!!
    }

    /**
     * 创建一个自定义的 Url，用于不再进行定制的修改
     *
     * session、加密是动态配置的
     */
    private fun <T> createApiService(
        apiService: Class<T>,
        baseUrl: String? = null,
        isOpenLog: Boolean,
        prettyJsonPrinting: Boolean = true
    ): T {
        if (baseUrl == null) {
            throw IllegalStateException("请先完成 ApiServiceHolder 的初始化工作！！！")
        }
        return NetworkFactory<T>()
            .setLogLevel(isOpenLog = isOpenLog, level = LogConfig.BODY)
            .setPrettyJsonPrinting(prettyJsonPrinting)
            .addInterceptor(HeaderInterceptor(headers))
            .addInterceptor(CommonParamsInterceptor())
            .addLogInterceptor(LogInterceptor())
            .setApiService(apiService)
            .setBaseUrl(baseUrl)
            .create()
    }
}
